<template>
  <div class="video-call-page">
    <VideoCall
      v-model="isOpen"
      :target-user-id="targetUserId"
      :target-name="targetName"
      :current-user-id="currentUserId"
      :get-user-initial="getUserInitial"
      :is-voice-only="isVoiceOnly"
      @call-ended="handleCallEnded"
      @switch-mode="handleSwitchMode"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import VideoCall from '@/components/video-call/VideoCall.vue'
import { isTauri } from '@/services/secure-storage'
import { closeVideoCallWindow } from '@/services/video-call-window'

// 从 URL 参数获取数据
const targetUserId = ref('')
const targetName = ref('')
const currentUserId = ref('')
const isVoiceOnly = ref(false)
const isOpen = ref(true)

// 获取用户首字母（简化版，实际应该从 store 获取）
const getUserInitial = (userId: string): string => {
  // 这里应该从用户数据中获取，暂时返回首字符
  return userId.charAt(0).toUpperCase()
}

// 处理通话结束
const handleCallEnded = async () => {
  isOpen.value = false
  // 延迟关闭窗口，让用户看到结束动画
  setTimeout(async () => {
    if (isTauri()) {
      await closeVideoCallWindow()
    } else {
      window.close()
    }
  }, 500)
}

// 处理模式切换
const handleSwitchMode = async (event: { isVoiceOnly: boolean }) => {
  isVoiceOnly.value = event.isVoiceOnly
  
  // 更新 URL 参数
  const urlParams = new URLSearchParams(window.location.search)
  urlParams.set('isVoiceOnly', String(event.isVoiceOnly))
  const newUrl = `${window.location.pathname}?${urlParams.toString()}`
  window.history.replaceState({}, '', newUrl)
  
  // 如果是独立窗口，通知窗口服务更新标题
  if (isTauri()) {
    const { updateVideoCallWindowMode } = await import('@/services/video-call-window')
    await updateVideoCallWindowMode(event.isVoiceOnly, targetName.value)
  }
}

// 监听窗口关闭和模式切换事件
onMounted(() => {
  // 从 URL 参数获取数据
  const urlParams = new URLSearchParams(window.location.search)
  targetUserId.value = urlParams.get('targetUserId') || ''
  targetName.value = decodeURIComponent(urlParams.get('targetName') || '')
  currentUserId.value = urlParams.get('currentUserId') || ''
  isVoiceOnly.value = urlParams.get('isVoiceOnly') === 'true'
  
  // 监听 Tauri 窗口关闭事件和模式切换事件
  if (isTauri()) {
    import('@tauri-apps/api/window').then(({ getCurrentWindow, listen }) => {
      const window = getCurrentWindow()
      
      // 监听窗口关闭
      window.listen('tauri://close-requested', () => {
        handleCallEnded()
      })
      
      // 监听模式切换事件
      listen('switch-call-mode', (event: any) => {
        const { isVoiceOnly } = event.payload || {}
        if (typeof isVoiceOnly === 'boolean') {
          handleSwitchMode({ isVoiceOnly })
        }
      })
    })
  }
  
  // 监听 URL 变化（用于窗口导航更新）
  const checkUrlParams = () => {
    const urlParams = new URLSearchParams(window.location.search)
    const newIsVoiceOnly = urlParams.get('isVoiceOnly') === 'true'
    if (newIsVoiceOnly !== isVoiceOnly.value) {
      isVoiceOnly.value = newIsVoiceOnly
    }
  }
  
  // 定期检查 URL 参数变化（用于窗口导航）
  let urlCheckInterval: ReturnType<typeof setInterval> | null = null
  
  urlCheckInterval = setInterval(checkUrlParams, 500)
  
  // 清理函数
  return () => {
    if (urlCheckInterval) {
      clearInterval(urlCheckInterval)
    }
  }
})

onUnmounted(() => {
  // 清理资源已在 onMounted 的返回函数中处理
})
</script>

<style lang="sass" scoped>
.video-call-page
  width: 100vw
  height: 100vh
  margin: 0
  padding: 0
  overflow: hidden
</style>

